﻿@model RDBMSMappingConfigViewModel



<zone Name="Title">
    <h1>@RenderTitleSegments(T["Mapping to relational database"])</h1>
</zone>
<div id="vueRDBMSForm">
    <form v-loading="loading" asp-action="CreateOrEdit" method="post" class="no-multisubmit">
        <input type="hidden" asp-for="Id" />
      @*  <div class="row">
            <div class="form-group col-md-4" asp-validation-class-for="ConfigName">
                <label asp-for="ConfigName">@T["Configuration Name"]</label>
                <input asp-for="ConfigName" class="form-control" type="text" />

            </div>
            <div class="form-group col-md-4" asp-validation-class-for="SyncMappingDeriction">
                <label asp-for="SyncMappingDeriction">@T["Mapping Deriction"]</label>
                <select asp-for="SyncMappingDeriction" class="form-control">
                    <option value="OrchardCoreToRDBMS">OrchardCore To RDBMS</option>
                    <option value="RDBMSToOrchardCore">RDBMS To OrchardCore</option>
                    <option value="TwoWay">Two Way</option>
                </select>
                <span class="hint">@T["Sync mapping deriction."]</span>
            </div>
        </div>*@

        <div class="row">
           @* <div class="form-group col-md-4" asp-validation-class-for="ContentTypeName">
                <label asp-for="ContentTypeName">@T["Content Type"]</label>
                <select asp-for="ContentTypeName" class="form-control">
                </select>
                <span class="hint">@T["Select a content type."]</span>
            </div>*@
            <div class="form-group col-md-4" asp-validation-class-for="ContentTypeName">

                <label asp-for="ConnectionConfigId">@T["Connection Config"]</label>
                @* <select asp-for="ConnectionConfigId" @change="loadAllTables" class="form-control"> </select> *@
                <el-select clearable v-model="model.connectionConfigId" style="width:100%" @@change="loadAllTables"
                           filterable placeholder="请选择">
                    <el-option v-for="item in allDbConnecton" :key="item.configId" :label="item.configName"
                               :value="item.configId">
                    </el-option>
                </el-select>

                <span class="hint">@T["Select a database connection config."]</span>
            </div>
        </div>
        <div class="form-group" asp-validation-class-for="TargetTable">
            <label asp-for="TargetTable">@T["Target Table"]</label>
            <input type="hidden" asp-for="TargetTable" />
            <div>
                <el-select v-model="model.tableName" :remote-method="loadAllTables" :loading="loading" remote
                           style="width:100%" filterable placeholder="请选择">
                    <el-option v-for="item in allTables" :key="`${item.schema}.${item.name}`"
                               :label="`[${item.schema}].[${item.name}]`" :value="`${item.schema}.${item.name}`">
                    </el-option>
                </el-select>
            </div>
            <span asp-validation-for="TargetTable"></span>
            <span class="hint">@T["选择表或者视图"]</span>
        </div>
        <div class="form-group">
            @*<button class="btn btn-success" type="button" id="btnGetTable">@T["Generate Table Mapping"]</button>*@
            <button class="btn btn-success" type="button" @@click="generateRecipe">@T["Generate ContentType"]</button>
            <button class="btn btn-primary" type="button" @@click="updateContentType">@T["Update ContentType"]</button>

        </div>

        <div class="form-group">
            <label>@T["Type Mapping Recipe"]</label><br />
            <div id="MappingData_editor" style="min-height: 400px;" class="form-control"></div>
            <input asp-for="MappingData" type="hidden" id="MappingData" v-model="recipeText" rows="12"
                   class="form-control"/>

        </div>

    </form>
</div>

<script asp-name="monaco" depends-on="admin" at="Foot"></script>
<script at="Foot" asp-name="elementUI" depends-on="vuejs"></script>


<style asp-name="element-theme-chalk" at="Head"></style>
<script at="Foot" asp-name="vuejs"></script>
<script at="Foot" depends-on="elementUI monaco">
    var monacoEditor;
    new Vue({
        el: '#vueRDBMSForm',
        data: function () {
            return {
                allDbConnecton: [],
                allTables: [],
                model: {
                    connectionConfigId: "",
                    tableName: ""
                },
                VerificationToken:$("input[name='__RequestVerificationToken']").val(),
                recipeText: "", 
                loading: false,
                tableFilter: {
                    connectionConfigId: "",
                    filterText: '@Model.MappingData',
                    maxResultCount: 20,
                    VerificationToken:$("input[name='__RequestVerificationToken']").val()
                }
            }
        },
        mounted() {
            this.loadConnections();
            this.VerificationToken=$("input[name='__RequestVerificationToken']").val()
            require(['vs/editor/editor.main'], () => {
                var settings = {
                    "automaticLayout": true,
                    "language": "json"
                };

                var html = document.getElementsByTagName("html")[0];
                const mutationObserver = new MutationObserver(setTheme);
                mutationObserver.observe(html, { attributes: true });

                function setTheme() {
                    var theme = html.dataset.theme;
                    if (theme === "darkmode") {
                        monaco.editor.setTheme('vs-dark')
                    } else {
                        monaco.editor.setTheme('vs')
                    }
                }
                setTheme();
                monacoEditor = monaco.editor.create(document.getElementById('@Html.IdFor(x => x.MappingData)_editor'), settings);
                monacoEditor.getModel().setValue(this.recipeText);

            });
        },
        methods: {
            loadConnections() {
                $.get("@Href("~/api/RDBMS/GetAllDbConnecton")",{  __RequestVerificationToken: $("input[name='__RequestVerificationToken']").val()}, (data) => {
                    this.allDbConnecton = data.result;
                })
            },
            loadAllTables(filterText) {
                if (this.model.connectionConfigId) {
                    this.tableFilter.connectionConfigId = this.model.connectionConfigId;
                    this.tableFilter.filterText = filterText;
                    this.loading = true;
                    $.get("@Href("~/api/RDBMS/GetAllTables")", this.tableFilter, (data, status) => {
                        if (status != "success") {
                            console.log(status)
                            this.$message("查询失败")
                        } else {
                            this.allTables = data.result;
                        }
                        this.loading = false;
                    })
                } else {
                    this.allTables = []
                }
            },
            generateRecipe() {
                this.loading = true;
                $.get("@Href("~/api/RDBMS/GenerateRecipe")", {
                    connectionConfigId: this.model.connectionConfigId,
                    tableName: this.model.tableName
                }, (data, status) => {
                    console.log(status)
                    if (status != "success") {
                        this.$message("查询失败")
                    } else {
                        this.recipeText = JSON.stringify(data.result);
                        monacoEditor.getModel().setValue(data.result);
                        monacoEditor.getAction(['editor.action.formatDocument'])._run();
                    }
                    this.loading = false;
                })
            },
            updateContentType() {
                this.recipeText = monacoEditor.getModel().getValue()
                if (!this.recipeText) {
                    this.$message.error("mapping is empty!")
                    return
                }
                console.log("this.recipeText", this.recipeText)
                this.loading = true; 
                $.ajax({
                    url: "@Href("~/api/RDBMS/ImportDeploymentPackage")",
                    type: "POST",
                    contentType: "application/json",//指定消息请求类型
                    data:JSON.stringify({
                        "json": this.recipeText
                    }),
                    success: (data) => {
                        this.$message.success("生成成功！")
                    }, error: (data) => {
                        this.$message.error("生成失败")
                    }, complete: () => {
                        this.loading = false;
                    }
                })
            },
            onSubmit() {

            }
        }
    })
</script>



